package com.b2c.handler;

import exception.ApiLimitException;
import exception.EmailException;
import result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static content.common.ResultMessage.EMAIL_SEND_FAIL;

@RestControllerAdvice
public class GlobalExcpetionHandler {
    /**
     * 发送邮箱出现的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(EmailException.class)
    public Result emailException(EmailException e) {
        return Result.fail(EMAIL_SEND_FAIL);
    }

    // <1> 处理 form data方式调用接口校验失败抛出的异常
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return Result.success(collect.toString());
    }

    // <2> 处理 json 请求体调用接口校验失败抛出的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return Result.fail(collect.toString());
    }

    // <3> 处理单个参数校验失败抛出的异常
    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect = constraintViolations.stream()
                .map(o -> o.getMessage())
                .collect(Collectors.toList());
        return Result.success(collect.toString());
    }

    //处理接口限流的异常
    @ExceptionHandler(ApiLimitException.class)
    public Result apiLimitExceptionHandler(ApiLimitException e) {
        return Result.fail(e.getMessage());
    }
}
